﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using RoadFlow.Utility;

namespace RoadFlow.Mvc.Areas.RoadFlowCore.Controllers
{
    [Area("RoadFlowCore")]
    public class DocController : Controller
    {
        [Validate(CheckApp = false)]
        public IActionResult Index()
        {
            ViewData["queryString"] = Request.UrlQuery();
            return View();
        }

        [Validate(CheckApp = false)]
        public IActionResult Tree()
        {
            ViewData["appid"] = Request.Querys("appid");
            ViewData["tabid"] = Request.Querys("tabid");
            return View();
        }

        [Validate(CheckApp = false)]
        public string Tree1()
        {
            return new Business.DocDir().GetTreeJson(Current.UserId);
        }

        [Validate(CheckApp = false)]
        public string TreeRefresh()
        {
            string refreshId = Request.Querys("refreshid");
            return refreshId.IsGuid(out Guid guid) ? new Business.DocDir().GetRefreshJson(guid, Current.UserId) : "";
        }

        [Validate(CheckApp = false)]
        public IActionResult List()
        {
            Guid userId = Current.UserId;
            string dirid = Request.Querys("dirid");
            Business.DocDir docDir = new Business.DocDir();
            Model.DocDir docDirModel = dirid.IsGuid(out Guid guid) ? docDir.Get(guid) : null;
            ViewData["isPublish"] = docDir.IsPublish(docDirModel, userId) ? "1" : "0";//是否有以布权限
            ViewData["isManage"] = docDir.IsManage(docDirModel, userId) ? "1" : "0";//是否有管理权限
            ViewData["query"] = "dirid=" + Request.Querys("dirid") + "&appid=" + Request.Querys("appid")
                + "&tabid=" + Request.Querys("tabid") + "&isnoread=" + Request.Querys("isnoread");
            ViewData["dirId"] = Request.Querys("dirid");//当前栏目ID
            ViewData["isNoRead"] = "0";//是否是查询未读文档
            return View();
        }

        [Validate(CheckApp = false)]
        public IActionResult DirEdit()
        {
            string dirid = Request.Querys("dirid");
            string currentdirid = Request.Querys("currentdirid");
            Model.DocDir docDirModel = null;
            Business.DocDir docDir = new Business.DocDir();
            if (currentdirid.IsGuid(out Guid guid))
            {
                docDirModel = docDir.Get(guid);
            }
            if (null == docDirModel)
            {
                docDirModel = new Model.DocDir
                {
                    Id = Guid.NewGuid(),
                    ParentId = dirid.ToGuid()
                };
                docDirModel.Sort = docDir.GetMaxSort(docDirModel.ParentId);
            }

            ViewData["queryString"] = Request.UrlQuery();
            ViewData["parentName"] = docDir.GetName(docDirModel.ParentId);
            ViewData["refreshId"] = docDirModel.ParentId;
            return View(docDirModel);
        }

        [Validate(CheckApp = false)]
        [ValidateAntiForgeryToken]
        public string SaveDirEdit(Model.DocDir docDirModel)
        {
            if (!ModelState.IsValid)
            {
                return Tools.GetValidateErrorMessag(ModelState);
            }
            Business.DocDir docDir = new Business.DocDir();
            if (Request.Querys("currentdirid").IsGuid(out Guid guid))
            {
                var oldModel = docDir.Get(guid);
                string oldJSON = null == oldModel ? "" : oldModel.ToString();
                docDir.Update(docDirModel);
                Business.Log.Add("修改了文档栏目-" + docDirModel.Name, type: Business.Log.Type.系统管理, oldContents: oldJSON, newContents: docDirModel.ToString());
            }
            else
            {
                docDir.Add(docDirModel);
                Business.Log.Add("添加了文档栏目-" + docDirModel.Name, docDirModel.ToString(), Business.Log.Type.系统管理);
            }
            return "保存成功!";
        }

        /// <summary>
        /// 删除栏目
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        [ValidateAntiForgeryToken]
        public string DeleteDir()
        {
            string dirid = Request.Querys("dirid");
            if (!dirid.IsGuid(out Guid did))
            {
                return "id错误!";
            }
            Business.DocDir docDir = new Business.DocDir();
            if (did == docDir.GetRoot().Id)
            {
                return "不能删除根栏目!";
            }
            if (docDir.HasDoc(did))
            {
                return "该栏目下有文档,不能删除!";
            }
            docDir.Delete(new Model.DocDir() { Id = did });
            Business.Log.Add("删除了文档栏目-" + dirid, "", Business.Log.Type.系统管理);
            return "删除成功!";
        }

        [Validate(CheckApp = false)]
        public IActionResult DocEdit()
        {
            string docid = Request.Querys("docid");
            string dirid = Request.Querys("dirid");
            Business.Doc doc = new Business.Doc();
            Model.Doc docModel = null;
            if (docid.IsGuid(out Guid guid))
            {
                docModel = doc.Get(guid);
            }
            if (null == docModel)
            {
                docModel = new Model.Doc
                {
                    Id = Guid.NewGuid(),
                    DirId = dirid.ToGuid(),
                    WriteTime = DateExtensions.Now,
                    WriteUserID = Current.UserId,
                    WriteUserName = Current.UserName,
                    ReadCount = 0,
                    Rank = 0
                };
                docModel.DirName = new Business.DocDir().GetName(docModel.DirId);
                
            }
            string query = "dirid=" + Request.Querys("dirid") + "&appid=" + Request.Querys("appid") + "&tabid=" + Request.Querys("tabid") +
                "&isnoread=" + Request.Querys("isnoread") + "&pagesize=" + Request.Querys("pagesize") + "&pagenumber="
                + Request.Querys("pagenumber");
            ViewData["query"] = query;
            ViewData["docid"] = docid;
            ViewData["rank"] = doc.GetRankOptions(docModel.Rank);
            return View(docModel);
        }

        [Validate(CheckApp = false)]
        [ValidateAntiForgeryToken]
        public string SaveDocEdit(Model.Doc docModel)
        {
            if (!ModelState.IsValid)
            {
                return Tools.GetValidateErrorMessag(ModelState);
            }
            Business.Doc doc = new Business.Doc();
            List<Model.User> users = new List<Model.User>();
            if (docModel.ReadUsers.IsNullOrWhiteSpace())
            {
                //如果没有指定阅读人员，则是有该栏目阅读权限的人员
                var docDir = new Business.DocDir().Get(docModel.DirId);
                if (null != docDir)
                {
                    users = new Business.Organize().GetAllUsers(docDir.ReadUsers);
                }
            }
            else
            {
                users = new Business.Organize().GetAllUsers(docModel.ReadUsers);
            }
            if (!users.Any())
            {
                return "没有阅读人员!";
            }
            if (Request.Querys("docid").IsGuid(out Guid guid))
            {
                var oldModel = doc.Get(guid);
                string oldJSON = null == oldModel ? "" : oldModel.ToString();
                doc.Update(docModel, users);
                Business.Log.Add("修改了文档-" + docModel.Title, type: Business.Log.Type.系统管理, oldContents: oldJSON, newContents: docModel.ToString());
            }
            else
            {
                doc.Add(docModel, users);
                Business.Log.Add("添加了文档-" + docModel.Title, docModel.ToString(), Business.Log.Type.系统管理);
            }
            return "保存成功!";
        }

        /// <summary>
        /// 删除文档
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        [ValidateAntiForgeryToken]
        public string DocDelete()
        {
            string docid = Request.Querys("docid");
            if (!docid.IsGuid(out Guid docId))
            {
                return "id错误!";
            }
            new Business.Doc().Delete(docId);
            Business.Log.Add("删除了文档-" + docid, "", Business.Log.Type.系统管理);
            return "删除成功!";
        }

        [Validate(CheckApp = false)]
        public string Query()
        {
            string Title = Request.Forms("Title1");
            string Date1 = Request.Forms("Date1");
            string Date2 = Request.Forms("Date2");
            string dirid = Request.Querys("dirid");
            string sidx = Request.Forms("sidx");
            string sord = Request.Forms("sord");
            string isnoread = Request.Querys("isnoread");

            int size = Tools.GetPageSize();
            int number = Tools.GetPageNumber();
            bool isAsc = "asc".EqualsIgnoreCase(sord);
            string order = (sidx.IsNullOrEmpty() ? "Rank,WriteTime" : sidx) + " " + (sord.IsNullOrEmpty() ? "DESC" : sord);
            Business.DocDir docDir = new Business.DocDir();
            if (dirid.IsGuid(out Guid typeId))
            {
                var childsId = docDir.GetAllChildsId(typeId);
                dirid = childsId.JoinSqlIn();
            }
            int read = "1".Equals(isnoread) ? 0 : -1;//1表示查询未读文档
            Guid userId = Current.UserId;
            var docDt = new Business.Doc().GetPagerList(out int count, size, number, userId, Title, dirid, Date1, Date2, order, read);
            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            Business.Dictionary dictionary = new Business.Dictionary();
            Business.DocUser docUser = new Business.DocUser();
            foreach (System.Data.DataRow dr in docDt.Rows)
            {
                string title = "<a href=\"javascript:void(0);\" class=\"blue\" onclick=\"showDoc('" + dr["Id"].ToString() + "');\">" + dr["Title"].ToString() + "</a>" +
                    (docUser.IsRead(dr["Id"].ToString().ToGuid(), userId) ? "" : "<img style=\"border:0;margin-left:4px;vertical-align:middle;\" src=\"/RoadFlowResources/images/loading/new.png\"/>");
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
                {
                    { "id", dr["Id"].ToString() },
                    { "Title",  title },
                    { "DirName", dr["DirName"].ToString() },
                    { "WriteUserName", dr["WriteUserName"].ToString() },
                    { "WriteTime", dr["WriteTime"].ToString().ToDateTime().ToDateTimeString() },
                    { "Rank", dictionary.GetTitle("system_documentrank", dr["Rank"].ToString()) },
                    { "ReadCount", dr["ReadCount"].ToString() }
                };
                jArray.Add(jObject);
            }
            return "{\"userdata\":{\"total\":" + count + ",\"pagesize\":" + size + ",\"pagenumber\":" + number + "},\"rows\":" + jArray.ToString() + "}";
        }

        [Validate(CheckApp = false)]
        public IActionResult Show()
        {
            string docid = Request.Querys("docid");
            string isread = Request.Querys("isread");//是否是阅读模式，阅读模式不显示工具栏
            if (!docid.IsGuid(out Guid docId))
            {
                return new ContentResult() { Content = "文档Id错误" };
            }
            Business.Doc doc = new Business.Doc();
            var docModel = doc.Get(docId);
            if (null == docModel)
            {
                return new ContentResult() { Content = "未找到当前文档" };
            }
            //更新阅读次数
            doc.UpdateReadCount(docModel);
            //更新状态为已读
            new Business.DocUser().UpdateIsRead(docModel.Id, Current.UserId, 1);
            var docDirModel = new Business.DocDir().Get(docModel.DirId);
            ViewData["queryString"] = Request.UrlQuery();
            ViewData["isPublish"] = new Business.DocDir().IsPublish(docDirModel, Current.UserId) ? "1" : "0";
            ViewData["tabId"] = Request.Querys("tabid");
            ViewData["isread"] = isread;
            return View(docModel);
        }

        /// <summary>
        /// 查看阅读情况
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public IActionResult ShowRead()
        {
            ViewData["queryString"] = Request.UrlQuery();
            return View();
        }

        [Validate(CheckApp = false)]
        public string QueryRead()
        {
            string sidx = Request.Forms("sidx");
            string sord = Request.Forms("sord");
            int size = Tools.GetPageSize(false);
            int number = Tools.GetPageNumber();
            bool isAsc = "asc".EqualsIgnoreCase(sord);
            string order = (sidx.IsNullOrEmpty() ? "UserId" : sidx) + " " + (sord.IsNullOrEmpty() ? "ASC" : sord);
            string docid = Request.Querys("docid");
            Business.DocUser docUser = new Business.DocUser();
            Business.Organize organize = new Business.Organize();
            Business.User user = new Business.User();
            System.Data.DataTable dt = docUser.GetDocReadPagerList(out int count, size, number, docid, order);
            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            foreach (System.Data.DataRow dr in dt.Rows)
            {
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
                {
                    { "UserId", user.GetName(dr["UserId"].ToString().ToGuid())},
                    { "Organize", user.GetOrganizeMainShowHtml(dr["UserId"].ToString().ToGuid()) },
                    { "IsRead", dr["IsRead"].ToString().Equals("0")?"未读":"已读" },
                    { "ReadTime", dr["ReadTime"].ToString().IsDateTime(out DateTime d) ? d.ToDateTimeString() : "" }
                };
                jArray.Add(jObject);
            }
            return "{\"userdata\":{\"total\":" + count + ",\"pagesize\":" + size + ",\"pagenumber\":" + number + "},\"rows\":" + jArray.ToString() + "}";
        }
    }
}